package com.ease.integration.telent;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;

import com.ease.common.util.Detect;

public class CommonsNetTelnetClient extends TelnetClient {

	private org.apache.commons.net.telnet.TelnetClient targetTelnetClient;

	private InputStream inputStream;
	private OutputStream outputStream;

	public boolean connect() throws RuntimeException {
		try {
			targetTelnetClient.connect(host, port);
			inputStream = targetTelnetClient.getInputStream();
			outputStream = targetTelnetClient.getOutputStream();
			return true;
		} catch (Exception e) {
			throw new RuntimeException("host=" + host + ", port=" + port, e);
		}
	}

	public boolean login() throws RuntimeException {

		this.response(usernamePrompt);
		this.request(username);
		this.response(passwordPrompt);
		this.request(password);
		this.response(null);

		return true;
	}

	public boolean disconnect() throws RuntimeException {
		try {
			targetTelnetClient.disconnect();
			return true;
		} catch (IOException e) {
			throw new RuntimeException("host=" + host + ", port=" + port, e);
		}
	}

	public void request(String command/* , boolean appendCrlf */) throws RuntimeException {
		try {
			// OutputStream outputStream = targetTelnetClient.getOutputStream();
			// outputStream.write((true==appendCrlf?appendEnterIfNecessary(command):command).getBytes());
			// outputStream.flush();

			PrintStream printStream = new PrintStream(outputStream);
			if (notEmpty(command)) {
				printStream.println(command);
			} else {
				printStream.println();
			}
			printStream.flush();
		} catch (Exception e) {
			throw new RuntimeException("host=" + host + ", port=" + port + ", command=" + command, e);
		}
	}

	public String response(String prompt) {
		StringBuilder stringBuilder = new StringBuilder();

		response(stringBuilder, prompt);

		return stringBuilder.toString();
	}

	public void response(StringBuilder response, String prompt) {

		try {
			byte[] buffer = new byte[BUFFER_LENGTH];
			int length = 0;
			do {
				length = inputStream.read(buffer);
				if (length > 0) {
					String returnString = new String(buffer, 0, length);

					// System.out.print(returnString);

					response.append(returnString);
					if (null != returnString) {

						if (response.toString().endsWith(this.morePrompt)) {
							request(" ");
							response(response, prompt);
						}

						String temp = response.toString();
						if (endsWith(temp, this.commandPrompt)) {
							break;
						}

						if (Detect.notEmpty(prompt)) {
							if (temp.endsWith(prompt)) {
								break;
							}
						}
					}
				}

			} while (length > 0);

		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @return the targetTelnetClient
	 */
	public org.apache.commons.net.telnet.TelnetClient getTargetTelnetClient() {
		return targetTelnetClient;
	}

	/**
	 * @param targetTelnetClient
	 *            the targetTelnetClient to set
	 */
	public void setTargetTelnetClient(org.apache.commons.net.telnet.TelnetClient targetTelnetClient) {
		this.targetTelnetClient = targetTelnetClient;
	}

	// public void waits(String prompt) {
	// InputStream inputStream = targetTelnetClient.getInputStream();
	// try {
	// byte[] buffer = new byte[1024];
	// int length = 0;
	//
	// do {
	// length = inputStream.read(buffer);
	// if (length > 0) {
	// String returnString = new String(buffer, 0, length);
	// System.out.print(returnString);
	// if (null != returnString && returnString.indexOf(prompt) > -1) {
	// return;
	// }
	//
	// }
	// } while (length >= 0);
	// } catch (IOException e) {
	// System.err.println("Exception while reading socket:" + e.getMessage());
	// }
	//
	// }

	// http://zhidao.baidu.com/question/469841224.html
	// java模拟的telnet,telnet一台交换机之后,发送了一条show running-config
	// 命令,结果是以more形式分屏显示的,我是以命令成功结束符获取结果的,现在的问题是,如何让他不用more形式,而是直接全部显示,或者能不能在发送一条命令,让他全部显示.如果连着发送空格的话,数量又不能确定,也很繁琐,结束符也不能确定.求指教啊
	// 获取返回内容，如果最后一行是
	//
	// ---more---
	//
	// 的内容，那么在发一个空格或任意字符
	//
	// 否则，肯定是结束了。
	// public String response1(StringBuilder response) {
	// InputStream inputStream = targetTelnetClient.getInputStream();
	//
	// try {
	// // StringWriter writer = new StringWriter();
	// // IOUtils.copy(inputStream, writer);
	// // return writer.toString();
	// byte[] buffer = new byte[BUFFER_LENGTH];
	// int length = 0;
	//
	// do {
	// length = inputStream.read(buffer);
	// if (length > 0) {
	// String returnString = new String(buffer, 0, length);
	// System.out.print(returnString);
	// // System.out.println("length" + length + "\n");
	// response.append(returnString);
	// if (null != returnString) {
	// if (returnString.endsWith(morePrompt)) {
	// send(null, " ");
	// response(response);
	// }
	// if (endsIn(returnString, commandPrompt)) {
	// break;
	// }
	// }
	// }
	//
	// } while (length >= 0);
	//
	// return response.toString();
	// } catch (IOException e) {
	// throw new RuntimeException(e);
	// }
	// }

}
